var bookAPI = (function($) {
	var userPicker;
	var hrDict = null,dict = {},nurseId,pinfo
	var ChangedProps = []
	$.init();
	
	$.plusReady(function() {
		baseSetup();
	});

	
	/*****获取人力资源数据****/
	function getPersonInfo() {
		plus.nativeUI.showWaiting("正在加载",{modal:false});
		var pdict = {'id':nurseId}
		var paramDict = {'method':'web.INMPersonComm:GetPerson','params':JSON.stringify(pdict),'type':'RecMethod'}
		//console.log(JSON.stringify(pdict))
		mui.DHCWebService(paramDict, function(result) {
			plus.nativeUI.closeWaiting();
			if (result.msgcode != '1') {
				mui.toast(result.msg);
			}else{
				hrDict = result.data;
				updateHRUI();
			}
		}, function(errorStr) {
			mui.toast(errorStr);
			plus.nativeUI.closeWaiting();
		});
	}
	function getChange(){
		var pdict = {'id':nurseId,appFlag:1}
		var paramDict = {'method':'web.INMPersonComm:RollbackToLastAudit','params':JSON.stringify(pdict),'type':'MethodNoFilter'}
		mui.DHCWebService(paramDict, function(result) {
			plus.nativeUI.closeWaiting();
			// console.log(JSON.stringify(result));
			if (result.msgcode != '1') {
				mui.toast(result.msg);
			}else{
				ChangedProps = result.data
				updateHRUIColor()
			}
		}, function(errorStr) {
			mui.toast(errorStr);
			plus.nativeUI.closeWaiting();
		});
	}
	function savePersonInfo(){
		/*入参:rw^人员id^flag^职务id^任职时间^身高^白衣号id^
		鞋号id^婚姻^学历id^学位id^政治面貌id^联系方式^
		护士注册证书号^专业技术职称^取得职称时间^现住址邮编^现住地址*/
		var perId = getLocalData('pinfo').rw;
		var xmlStr = '<Request>^'+perId+"^V"+'^'+dict.PersonheadshipDR+'^'+
			dict.PersonNurHeadDate+'^'+dict.PersonHeight+'^'+dict.PersonClothesNO+'^'+
			dict.PersonShoeNO+'^'+dict.Personmarriage+'^'+dict.PersonSchoolAgeDr+'^'+
			dict.PersonDegreeDR+'^'+dict.PersonPolitydr+'^'+dict.PersonTelHand+'^'+
			dict.PersonRegNo+'^'+dict.PersonProfPostDR+'^'+dict.PersonTechPostDate+'^'+
			dict.PersonPresentZipCode+'^'+dict.PersonAddress+'</Request>';
		plus.nativeUI.showWaiting("正在提交",{modal:false});
		postHttpRequest(xmlStr, 'nurse.class.saveperinfo', function(result) {
			plus.nativeUI.closeWaiting();
			mui.toast('提交成功');
			var saveBtn = document.getElementById('saveBtn');
			saveBtn.style.display = 'none';
			var hrBaseUl = document.getElementById('hrBaseUl');
			hrBaseUl.classList.add('review');
		}, function(errorStr) {
			mui.toast(errorStr);
			plus.nativeUI.closeWaiting();
		});
	}
	//更新人力资源界面 
	function updateHRUI() {
		mui('#hrBaseUl li').each(function (index,dom) {
			var type = dom.getAttribute('data-type')
			var keyStr = dom.id
			if (type && type != 'input') {
				keyStr = keyStr + 'Desc'
			}
			var value = hrDict[keyStr]
			if (keyStr == 'PerAddress') {
				value = hrDict['CurrentProvince']+hrDict['CurrentCity']+
					hrDict['CurrentArea']+hrDict['CurrentAddress']; 
			}
			dom.querySelector('.rightText').innerText = value
		})
	}
	function updateHRUIColor(){
		var UL = mui('#hrBaseUl')[0]
		// console.log(JSON.stringify(ChangedProps));
		for (var i = 0; i < ChangedProps.length; i++) {
			var dom = mui('#'+ChangedProps[i])[0]
			if (dom) {
				UL.classList.add('review')
				dom.classList.add('change');
			}
		}
	}
	
	//获取下拉列表的数据
	function getPickerData(liId){
		var liDom = document.getElementById(liId);
		var type = liDom.getAttribute('data-type');
		plus.nativeUI.showWaiting('正在加载',{modal:false});
		var pdict = {'type':type}
		var paramDict = {'method':'web.INMDBComm:FindPubCode','params':JSON.stringify(pdict),'type':'Query'}
			// console.log(JSON.stringify(pdict))
		mui.DHCWebService(paramDict, function(result) {
			// console.log(JSON.stringify(result))
			plus.nativeUI.closeWaiting();
			var dataArr = result.data;
			for (var i = 0; i < dataArr.length;i++) {
				dataArr[i]['text'] = dataArr[i]['SubDesc']; //SubValue 
			}
			showPickerUI(liId,dataArr);
		}, function(errorStr) {
			mui.toast(errorStr);
			plus.nativeUI.closeWaiting();
		});		
	}
	
	function showPickerUI(liId,dataArr){
		userPicker.setData(dataArr);
		userPicker.show(function(items){
			var textStr = items[0]['text'];
			if (hrDict[liId] != items[0]['SubValue']) {
				hrDict[liId] = items[0]['SubValue']
				hrDict[liId+'Desc'] = textStr
				mui('#'+liId+' .rightText')[0].innerText = textStr
				mui('#'+liId)[0].classList.add('change')
				isSaveBtnShow();
			}
		});
	}
	
	//选择日期
	function selectDatePicker(liDom) {
		var _self = liDom;
		if(_self.picker) {
			_self.picker.show(function(rs) {
				var text = liDom.querySelector('.rightText').innerText
				if (text != rs.text) {
					liDom.querySelector('.rightText').innerText = rs.text
					liDom.classList.add('change')
					isSaveBtnShow();
				}
				_self.picker.dispose();
				_self.picker = null;
			});
		} else {
			_self.picker = new mui.DtPicker({
				type: "date",
				beginDate: new Date(1920, 01, 01),//设置开始日期 
				// endDate: new Date(2016, 04, 25),//设置结束日期
			});
			_self.picker.show(function(rs) {
				var text = liDom.querySelector('.rightText').innerText
				if (text != rs.text) {
					liDom.querySelector('.rightText').innerText = rs.text
					liDom.classList.add('change')
					isSaveBtnShow();
				}
				_self.picker.dispose();
				_self.picker = null;
			});
		}
	}
	//选择日期
	function iOSSelectDatePicker(liDom) {
		plus.nativeUI.pickDate(function(e) {
			var d = e.date;
			var dateStr = d.getFullYear()+'-'
			if (d.getMonth() < 9) {
				dateStr += '0'
			}
			dateStr += (d.getMonth() + 1)+'-'
			if (d.getDate() < 10) {
				dateStr += '0'
			}
			dateStr += d.getDate()
			var text = liDom.querySelector('.rightText').innerText
			if (text != dateStr) {
				liDom.querySelector('.rightText').innerText = dateStr
				liDom.classList.add('change')
				isSaveBtnShow();
			}
		}, function(e) {}, {
			minDate: new Date(1920, 01, 01),//设置开始日期 
		});
	}
	
	function showInputPopover(liId){
		var tip = mui('#'+liId +' .underLine')[0].innerText
		var popover = document.getElementById('popover');
		popover.setAttribute('data-type',liId);
		var title = popover.querySelector('.title');
		title.innerText = '填写新的' + tip;
		var inputDom = document.getElementById('input');
		inputDom.value = '';
		mui('#popover').popover('toggle');
	}
	
	function popoSureBtnTapped(){
		var inputDom = document.getElementById('input');
		inputDom.blur()
		var valueStr = inputDom.value;
		if (valueStr.length == 0) {
			mui.toast('请输入');
			return
		}
		var popover = document.getElementById('popover');
		var liId = popover.getAttribute('data-type');
		mui('#'+liId)[0].classList.add('change')
		mui('#'+liId)[0].querySelector('.rightText').innerText = valueStr
		mui('#popover').popover('toggle');
		isSaveBtnShow();
	}
	
	//人力资源子项被点击
	function hrBaseLiTapped(){
		var hrBaseUl = document.getElementById('hrBaseUl');
		var hrClass = hrBaseUl.getAttribute('class');
		if (hrClass.indexOf('review') != -1) {
			mui.toast('您的上次修改经审批后才能再次编辑');
			return;
		}else if (hrDict == null) {
			return;
		}
		var idStr = this.id;
		var type = this.getAttribute('data-type')
		if (!type) {
			return
		}
		var liDom = this;
		switch (type){
			case 'input':
				if(idStr == 'PerAddress'){
					showAddressInputPopover();
				}else{
					showInputPopover(idStr);
				}
				break;
			case 'date':
				if (plus.os.name == 'iOS') {
					iOSSelectDatePicker(liDom)
				}else{
					selectDatePicker(liDom);
				}
				break;
			default:
				getPickerData(idStr);
				break;
		}
	}
	
	function isSaveBtnShow(){
		var saveBtn = document.getElementById('saveBtn');
		var hrBaseUl = document.getElementById('hrBaseUl');
		var change = hrBaseUl.querySelector('li.change')
		if (change != null) {
			// saveBtn.style.display = 'block';
		}else{
			saveBtn.style.display = 'none';
		}
	}
	
	function baseSetup() {
		if (plus.os.name == 'iOS') {
			userPicker = new mui.xhPicker(1,'请选择婚姻状况','pickerId');
		}else{
			userPicker = new mui.PopPicker();
		}
		mui('.mui-scroll-wrapper').scroll();
		var head = document.getElementById('head');
		head.addEventListener('tap', headLiTapped,false);
		defaultImg();
		
		document.getElementById("head-img1").addEventListener('tap', function(e) {
			// e.stopPropagation();
			return
			var Internet = this.src
			// mui.previewImage({
			//     images: [Internet] // 需要预览的图片http链接列表
			// });
			var imgData = [{'Internet':this.src}]
			var imgPlay = mui.openWindow({
				url:'../Home/imgPlay.html',
				id:'imgPlay',
				extras:{
					index:0,
					sourceData:imgData
				}
			});
			imgPlay.addEventListener('close', function() {
				plus.navigator.setStatusBarBackground('#24AF96');
			})
		});
		hrBaseSetup();
		//var today = getTodayStr();
		getPersonInfo();
		getChange()
	}
	
	function hrBaseSetup() {
		var pinfo = app.getState();
		nurseId = pinfo.loginPerID
		// console.log(JSON.stringify(pinfo));
		//姓名
		mui('#nurseName')[0].innerText = pinfo['loginName'];
		//工号
		mui('#account')[0].innerText = pinfo['usercode'];
		//部门
		mui('#userLoc')[0].innerText = pinfo.loginWardDesc
		//点击可以修改的部分
		// mui('#hrBaseUl').on('tap','li',hrBaseLiTapped) 
		
		//popover上的确定按钮
		var popoSure = document.getElementById('popoSure');
		popoSure.addEventListener('tap',popoSureBtnTapped, false);
		
		mui('#addressPop').on('tap','#addressSure',addressPopoSureBtnTapped) 
		var saveBtn = document.getElementById('saveBtn');
		saveBtn.addEventListener('tap', savePersonInfo, false);
	}
	function showAddressInputPopover(){
		var popover = document.getElementById('addressPop');
		mui('#addressPop input').each(function (index,dom) {
			dom.value = hrDict[dom.id]
		})
		mui('#addressPop').popover('toggle');
	}
	
	function addressPopoSureBtnTapped(){
		var doms = mui('#addressPop input')
		var oldText = ''
		for (var i = 0; i < doms.length; i++) {
			var dom = doms[i]
			dom.blur()
			if (dom.value == '') {
				mui.toast('请输入')
				return false
			}
			if (hrDict[dom.id] != dom.value) {
				mui('#PerAddress')[0].classList.add('change')
			}
			hrDict[dom.id] = dom.value
		}
		var rightText = mui('#PerAddress .rightText')[0]
		rightText.innerText = hrDict['CurrentProvince']+hrDict['CurrentCity']+
			hrDict['CurrentArea']+hrDict['CurrentAddress']; 
		mui('#addressPop').popover('toggle');
		isSaveBtnShow();
	}
	function headLiTapped(){
		if(mui.os.plus) {
			var a = [{title: "拍照"}, {title: "从手机相册选择"}];
			plus.nativeUI.actionSheet({
				title: "修改头像",
				cancel: "取消",
				buttons: a
			}, function(b) {
				switch(b.index) {
					case 0:
						break;
					case 1:
						getImage();
						break;
					case 2:
						galleryImg();
						break;
					default:
						break
				}
			});
		}
	}
	function defaultImg() {
		if(mui.os.plus) {
			plus.io.resolveLocalFileSystemURL("_doc/head.jpg", function(entry) {
				var s = entry.fullPath + "?version=" + new Date().getTime();
				document.getElementById("head-img1").src = s;
			}, function(e) {
				document.getElementById("head-img1").src = '../dependence/user/images/head.jpg';
			})
		} else {
			document.getElementById("head-img1").src = '../dependence/user/images/head.jpg';
		}
	}
	
	function getImage() {
		var c = plus.camera.getCamera();
		c.captureImage(function(e) {
			plus.io.resolveLocalFileSystemURL(e, function(entry) {
				var s = entry.toLocalURL() + "?version=" + new Date().getTime();
				// console.log(s);
				document.getElementById("head-img1").src = s;
				var user = plus.webview.getWebviewById('user.html');
				user.evalJS('defaultImg()');
			}, function(e) {
				console.log("读取拍照文件错误：" + e.message);
			});
		}, function(s) {
			console.log("error" + s);
		}, {
			filename: "_doc/head.jpg"
		})
	}
	
	
	
	function galleryImg() {
		plus.gallery.pick(function(a) {
			plus.io.resolveLocalFileSystemURL(a, function(entry) {
				plus.io.resolveLocalFileSystemURL("_doc/", function(root) {
					root.getFile("head.jpg", {}, function(file) {
						//文件已存在
						file.remove(function() {
							entry.copyTo(root, 'head.jpg', function(e) {
									var e = e.fullPath + "?version=" + new Date().getTime();
									document.getElementById("head-img1").src = e;
									//变更大图预览的src
									//目前仅有一张图片，暂时如此处理，后续需要通过标准组件实现
									document.querySelector("#__mui-imageview__group .mui-slider-item img").src = e + "?version=" + new Date().getTime();;
									var user = plus.webview.getWebviewById('user.html');
									user.evalJS('defaultImg()');
								},
								function(e) {
									console.log('copy image fail:' + e.message);
								});
						}, function() {
							console.log("delete image fail:" + e.message);
						});
					}, function() {
						//文件不存在
						entry.copyTo(root, 'head.jpg', function(e) {
								var path = e.fullPath + "?version=" + new Date().getTime();
								document.getElementById("head-img1").src = path;
								//变更大图预览的src
								//目前仅有一张图片，暂时如此处理，后续需要通过标准组件实现
								document.querySelector("#__mui-imageview__group .mui-slider-item img").src = path;
								var user = plus.webview.getWebviewById('user.html');
								user.evalJS('defaultImg()');
							},
							function(e) {
								console.log('copy image fail:' + e.message);
							});
					});
				}, function(e) {
					console.log("get _www folder fail");
				})
			}, function(e) {
				console.log("读取拍照文件错误：" + e.message);
			});
		}, function(a) {}, {
			filter: "image"
		})
	};
})(mui);


/* 人力资源
原始数据
	职务:'PersonheadshipDR':'护士长'  任职时间:PersonNurHeadDate:''  身高:PersonHeight:165
	白衣号:PersonClothesNO:L          鞋号:PersonShoeNO:38          婚姻:Personmarriage:已婚
	学历:PersonSchoolAgeDr:本科       学位:PersonDegreeDR:学士      政治面貌:PersonPolitydr:群众
	联系方式:PersonTelHand:13810703725  护士注册证书号:PersonRegNo:200911005026
	专业技术职称:PersonProfPostDR:''    取得职称时间:PersonTechPostDate:''
	现住址邮编:PersonPresentZipCode:100350   现住地址:PersonAddress:'北京市东城区'  
 
 Flag="V" s FlagDesc="待审批"
	e  i Flag="A" s FlagDesc="审核通过"
	e  i Flag="R" s FlagDesc="已驳回"*/

/* 
 * 科研获奖/课题立项/护理专利/文章上报列表查询依据
 * 1.科研获奖--获奖日期
 * 2.课题立项--立项日期
 * 3.护理专利--发明申请日
 * 4.文章上报--发表日期
 */